home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 2 / Atari Mega Archive CD - Volume 2.iso / minix / up1510b.tgz / up1510b / src / lib / posix / opendir.c < prev    next >
C/C++ Source or Header  |  1990-07-19  |  1KB  |  59 lines

  1. /* opendir -- open a directory stream    Author: D.A. Gwyn */
  2.  
  3. /*    last edit:    27-Oct-1988    D A Gwyn    */
  4.  
  5. #include <lib.h>
  6. #include <sys/stat.h>
  7. #include <dirent.h>
  8. #include <unistd.h>
  9. #include <stdlib.h>
  10. #include <fcntl.h>
  11.  
  12. #define DULL (DIR *) 0
  13. #define CULL (char *) 0
  14.  
  15. typedef char *pointer;        /* (void *) if you have it */
  16.  
  17. #ifndef O_RDONLY
  18. #define    O_RDONLY    0
  19. #endif
  20.  
  21. #ifndef S_ISDIR            /* macro to test for directory file */
  22. #define    S_ISDIR( mode )        (((mode) & S_IFMT) == S_IFDIR)
  23. #endif
  24.  
  25. DIR *opendir(dirname)
  26. char *dirname;            /* name of directory */
  27. {
  28.   register DIR *dirp;        /* -> malloc'ed storage */
  29.   register int fd;        /* file descriptor for read */
  30.  
  31.   /* The following is PRIVATE just to keep the stack small. */
  32.   PRIVATE struct stat sbuf;    /* result of fstat() */
  33.  
  34.   if ((fd = open(dirname, O_RDONLY)) < 0)
  35.     return(DULL);        /* errno set by open() */
  36.  
  37.   if (fstat(fd, &sbuf) != 0 || !S_ISDIR(sbuf.st_mode)) {
  38.     (void) close(fd);
  39.     errno = ENOTDIR;
  40.     return(DULL);        /* not a directory */
  41.   }
  42.   if ((dirp = (DIR *) malloc(sizeof(DIR))) == DULL
  43.       || (dirp->dd_buf = (char *) malloc((unsigned) _DIRBUF)) == CULL){
  44.     register int serrno = errno;
  45.     /* Errno set to ENOMEM by sbrk() */
  46.  
  47.     if (dirp != (DIR *) DULL) free((pointer) dirp);
  48.  
  49.     (void) close(fd);
  50.     errno = serrno;
  51.     return(DULL);        /* not enough memory */
  52.   }
  53.   dirp->dd_fd = fd;
  54.   dirp->dd_magic = _DIR_MAGIC;    /* to recognize DIRs */
  55.   dirp->dd_loc = dirp->dd_size = 0;    /* refill needed */
  56.  
  57.   return(dirp);
  58. }
  59.